package com.starblink.comment

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.comment.bean.MoreCommentBean
import com.starblink.comment.bean.PostComment
import com.starblink.comment.bean.ReplyPostComment
import com.starblink.rocketreserver.DeletePostCommentMutation
import com.starblink.rocketreserver.FetchPostComments4SecondQuery
import com.starblink.rocketreserver.FetchPostCommentsQuery
import kotlinx.coroutines.launch

class PostCommentVM : BaseViewModel() {

    var mList: MutableLiveData<MutableList<Any>> =
        MutableLiveData(mutableListOf())

    var postId: String = ""
    var isLoadingMore: Boolean = false
    var pageNo = 1
    var secondPageNoMap: Map<String, Int> = mapOf()

    /**
     * 加载评论数据
     */
    fun getCommentList(isFirst: Boolean = true) {
        setStateLiveData(LoadAction(LoadAction.STATE_LOADING))
        if (isFirst) {
            mList.value = mutableListOf()
            pageNo = 1
        }
        isLoadingMore = true
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchPostCommentsQuery(
                    postId, Optional.present(pageNo), Optional.present(12),
                ), showDefaultLoading = isFirst
            )
            isLoadingMore = false
            if (response?.data != null && response.data!!.fetchPostComments != null && response.data!!.fetchPostComments!!.isNotEmpty()) {
                loadSuccess()
                var postList = response.data!!.fetchPostComments
                var list = mutableListOf<Any>()
                postList!!.forEach { e ->
                    val commentF = e.postCommentF
                    list.add(commentF.toJson().toBean<PostComment>())
                    val secondCommentTotal = commentF.secondCommentTotal
                    if (e.secondCommentList != null) {
                        for (i in e.secondCommentList!!.indices) {
                            val item = e.secondCommentList!![i]?.postCommentF
                            if (item != null && i < 2) {
                                list.add(item.toJson().toBean<ReplyPostComment>())
                            }
                        }
                    }
                    if (secondCommentTotal > 2) {
                        secondPageNoMap = mapOf(commentF.id to 1)
                        list.add(
                            MoreCommentBean(
                                secondCommentTotal,
                                commentF.id
                            )
                        )//增加还有几个评论model 可点击展开更多
                    }
                }
                pageNo++
                if (list.isNotEmpty()) {
                    mList.value?.addAll(list)
                    mList.value = mList.value
                }
            } else {
                if (pageNo == 1) {
                    loadNoData()
                } else {
                    loadSuccess()
                }
            }
        }
    }

    /**
     * 加载二级评论数据
     */
    fun getSecondCommentList(commentId: String, commentIdx: Int) {
        var page = secondPageNoMap[commentId] ?: 1
        isLoadingMore = true
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchPostComments4SecondQuery(
                    commentId, Optional.present(page), Optional.present(12),
                ),
                showDefaultLoading = true
            )
            isLoadingMore = false
            if (response?.data != null && response.data!!.fetchPostComments4Second != null) {
                var postList = response.data!!.fetchPostComments4Second
                var list = arrayListOf<ReplyPostComment>()
                for (i in postList!!.indices) {
                    if (page == 1 && i < 2) {//去除第一页重复数据
                        continue
                    }
                    val item = postList[i].postCommentF
                    if (item != null) {
                        list.add(item.toJson().toBean<ReplyPostComment>())
                    }
                }
                if (list.isNotEmpty()) {
                    page += 1
                    secondPageNoMap = mapOf(commentId to page)
                    if (postList.size < 12) {//不足请求量判断没有更多评论
                        mList.value?.removeAt(commentIdx)
                        mList.value = mList.value
                    }
                    mList.value?.addAll(commentIdx, list)
                    mList.value = mList.value
                } else {
                    mList.value?.removeAt(commentIdx)
                    mList.value = mList.value
                }
            }
        }
    }

    /**
     * 删除自己评论
     */
    fun deleteComment(commentId: String, index: Int) {
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                DeletePostCommentMutation(
                    postCommentId = commentId
                ),
                showDefaultLoading = true
            )
            isLoadingMore = false
            if (response?.data != null && response.data!!.deletePostComment != null && response.data!!.deletePostComment) {
                mList.value?.removeAt(index)
                mList.value = mList.value
            }
        }
    }
}